/**
 * @file index.js
 * @description 路由配置文件，包含路由定义、导航守卫和权限控制
 * @module router/index
 */

import { createRouter, createWebHistory } from "vue-router";
import Layout from "../views/layout.vue";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { useUserStore } from '../stores/user';
import { useRouterStore } from '../stores/router';

/**
 * 生成面包屑导航数据
 * @param {Object} route - 当前路由对象
 * @param {Array} currentBreadcrumb - 当前面包屑数组
 * @returns {Array} 处理后的面包屑数组
 */
function generateBreadcrumb(route, currentBreadcrumb = []) {
  if (route.meta && route.meta.breadcrumb) {
    return [...currentBreadcrumb, ...route.meta.breadcrumb];
  }

  if (route.parent) {
    return generateBreadcrumb(route.parent, currentBreadcrumb);
  }

  return currentBreadcrumb;
}

const constantRoutes = [
  {
    path: "/",
    component: Layout,
    redirect: "/dashboard",
    children: [
      {
        path: "dashboard",
        name: "Dashboard",
        component: () => import("../views/dashboard.vue"),
        meta: {
          title: "仪表盘",
          icon: "HomeFilled",
          hidden: false
        }
      }
    ]
  },
  {
    path: "/login",
    component: () => import("../views/login/index.vue"),
    meta: { 
      title: "登录", 
      hidden: true 
    }
  },
  {
    path: "/profile",
    component: Layout,
    name: "个人中心",
    meta: {
      title: "个人中心",
      icon: "Avatar",
      hidden: false
    },
    redirect: "/profile/index",
    children: [
      {
        path: "index",
        component: () => import("../views/information/index.vue"),
        meta: {
          title: "个人中心",
          hidden: true
        }
      }
    ]
  },
  {
    path: "/:pathMatch(.*)*",
    redirect: "/404",
    meta: {
      hidden: true
    }
  }
];

// 导入模块化的路由配置
import { userRoutes } from './modules/user';
import { systemRoutes } from './modules/system';

// 动态路由
const asyncRoutes = [...userRoutes, ...systemRoutes];

/**
 * 创建路由实例
 * @description 配置路由模式、基础路由、滚动行为等
 */
const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes, // 初始只加载静态路由
  scrollBehavior: () => ({ y: 0 })
});

// 导出路由配置，供其他模块使用
export { constantRoutes, asyncRoutes };

// 配置 NProgress
NProgress.configure({ 
  easing: "ease", 
  speed: 600, 
  showSpinner: false 
});

/**
 * 全局前置守卫
 * @description 处理路由跳转前的权限验证、用户信息获取等
 */
router.beforeEach(async (to, from, next) => {
  NProgress.start();

  // 设置页面标题
  document.title = to.meta.title || "运维管理平台";

  // 如果是访问登录页，直接放行
  if (to.path === "/login") {
    next();
    return;
  }

  // 获取token
  const token = sessionStorage.getItem("token");
  if (!token) {
    next("/login");
    return;
  }

  // 获取用户信息和权限
  const userStore = useUserStore();
  const routerStore = useRouterStore();

  if (!userStore.userInfo) {
    try {
      // 获取用户信息
      await userStore.getUserInfo();
      console.log("用户信息获取成功:", userStore.userInfo);
      console.log("用户权限:", userStore.permissions);
      
      console.log('开始处理动态路由加载...');
      console.log('当前用户权限:', userStore.permissions);
      console.log('待过滤的动态路由配置:', asyncRoutes);

      // 根据权限过滤动态路由
      const accessRoutes = filterAsyncRoutes(asyncRoutes, userStore.permissions);
      console.log('根据权限过滤后的动态路由:', JSON.stringify(accessRoutes, null, 2));
      
      // 添加动态路由到路由实例
      accessRoutes.forEach(route => {
        console.log(`正在添加动态路由: ${route.path}`);
        router.addRoute(route);
      });
      
      // 更新store中的路由信息
      const allRoutes = [...constantRoutes, ...accessRoutes];
      routerStore.setDynamicRoutes(allRoutes);
      console.log(`动态路由加载完成，共计${allRoutes.length}个菜单`);
      
      // 重定向到目标路由
      next({ ...to, replace: true });
    } catch (error) {
      console.error("获取用户信息失败:", error);
      next("/login");
    }
    return;
  }

  next();
});

// 路由后置守卫
router.afterEach(() => {
  NProgress.done();
});

// 根据权限过滤路由
function filterAsyncRoutes(routes, permissions) {
  const res = [];

  routes.forEach(route => {
    const tmp = { ...route };
    console.log(`正在处理路由: ${tmp.path}`);
    console.log(`路由所需权限:`, tmp.meta?.permissions || '无');
    
    // 如果是超级管理员，直接添加所有路由
    if (permissions.includes('admin')) {
      console.log(`用户是超级管理员，允许访问路由: ${tmp.path}`);
      if (tmp.children) {
        console.log(`处理子路由: ${tmp.path}`);
        tmp.children = filterAsyncRoutes(tmp.children, permissions);
      }
      res.push(tmp);
    } else if (hasPermission(permissions, tmp)) {
      console.log(`用户具有访问权限，允许访问路由: ${tmp.path}`);
      if (tmp.children) {
        console.log(`处理子路由: ${tmp.path}`);
        tmp.children = filterAsyncRoutes(tmp.children, permissions);
        // 只添加有子路由的父级路由
        if (tmp.children.length > 0) {
          res.push(tmp);
        }
      } else {
        res.push(tmp);
      }
    } else {
      console.log(`用户无权访问路由: ${tmp.path}`);
    }
  });

  return res;
}

// 检查权限
function hasPermission(permissions, route) {
  if (route.meta && route.meta.permissions) {
    console.log(`检查路由权限: ${route.path}`);
    console.log('所需权限:', route.meta.permissions);
    console.log('用户权限:', permissions);
    const hasAccess = route.meta.permissions.some(permission => 
      permissions.includes(permission)
    );
    console.log(`权限检查结果: ${hasAccess ? '通过' : '未通过'}`);
    return hasAccess;
  }
  console.log(`路由 ${route.path} 无需权限检查`);
  return true;
}

export default router;